十六、react native 组件间通信,局部刷新

局部刷新对于性能提升太重要了。我举几个场景:

  1. 当员工在钉钉上填写了请假时长, 请假原因后, 提交按钮由disable变为enable.
  2. 滚动app界面上的list到某一位置时,更改toolbar的标题或者样式
    如果按不考虑性能做法: 我在page页设置state. 让提交按钮或者 toolbar直接 读这个this.state的值。触发时只要setState即可达到我们的要求。
    但问题是整个page页面都刷新了。我只想更改提交按钮但是请假时长,请假原因都做了render.如果页面很复杂。会给用户不好的体验。直接上代码:
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    export default class GatherDetailPage extends Component {

    render(){
    return(
    <View style={{flex: 1,flexDirection: 'column'}}>
    <LabelMedia
    ref='mediaRef'
    viewItem={viewItem}
    rightBtnImgSrc={imageSource}
    onRightBtnClicked={(inputValue, needSave) => {this.onRightBtnClicked(viewItem, inputValue, needSave)}}
    />
    <TextInput
    style={{width: '100%', height:60}}
    underlineColorAndroid={'transparent'}
    placeholder='你们这群ABC'
    placeholderTextColor='#bbb'
    multiline={false}
    onChangeText={(text) => {this.onTestChange(text)}}
    />
    </View>
    );
    }

    onTestChange(input) {
    this.refs.mediaRef.testStyle();
    }
    }
    在page页面中,竟然可以调用LabelMedia子控件的方法 testStyle。

LabelMedia.js代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
export default class LabelMedia extends Component {

constructor(props) {
super(props);

this.state = {
testColor:'transparent'
};
}

testStyle() {
this.setState({
testColor:'#f40'
})
}

render() {
return(
<View style={{
flexDirection: 'row',
width:'100%',
height: 80,
justifyContent: 'space-between',
alignItems: 'center',
backgroundColor:`${this.state.testColor}`
}}>
<Text
style={{
height: '100%',
fontSize: 15,
textAlign: 'center',
textAlignVertical: 'center',
justifyContent: 'center'
}}
></Text>
</View>
);
}
}

确实做到了局部刷新。即page页面不会调用render.只有 LabelMedia的render会被调用。